<?php

namespace App\Http\Controllers\Laifei\Work;

use App\Http\Controllers\Controller;
use App\Models\Common\Wechat;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Log;

class LaifeiWorkReSettlementController extends Controller
{

    /**
     * 红包重发
     */
    public function index()
    {
        $all = $this->all;

        $work_id = $all['work_id'];



        // 检查这个工单是否已经结算，最新的一次红包发送记录是否是已退回
        $last_settlement = DB::table('explore_settlement')->where('work_id', '=', $work_id)->latest()->first();
        $last_settlement = json_decode(json_encode($last_settlement), true);

        if (!$last_settlement) {
            return $this->setReturnJson(-1, '这个工单没有最近的红包');
        }

        if ($last_settlement['received'] !== 2) {
            return $this->setReturnJson(-1, '这个红包当前不能重发');
        }

        // 查询工单信息，重发这个红包
        $work_message = DB::table('explore_work')->where('work_id', '=', $work_id)->first();
        $work_message = json_decode(json_encode($work_message), true);

        $openid = DB::table('lottery_users')->where('we_id', '=', $work_message['receiver_we_id'])->value('openid');

        if ($openid !== $last_settlement['openid']) {
            Log::emergency(LaifeiWorkReSettlementController::class, ['last_settlement' => $last_settlement, 'work_message' => $work_message]);
            return $this->setReturnJson(-1, '数据异常，请联系研发检查问题',['last_settlement' => $last_settlement, 'work_message' => $work_message]);
        }

        // 更新结算单号
        $mchBillNo = LaifeiWorkSettlementController::billNo($work_id);

        try{
            DB::beginTransaction();

            // 查询探店佣金比例
            $service_fee_percent = DB::table('sys_setting')
                ->where('setting_key','=','service_fee')
                ->sharedLock()
                ->value('setting_value');
            // 服务费
            $service_fee = ceil($work_message['settlement_amount'] * $service_fee_percent / 100);
            // 红包金额
            $payment_amount = $work_message['settlement_amount'] - $service_fee;

            $insert = [
                'work_id'=>$work_id,
                'work_no'=>$work_message['work_no'],
                'mch_billno'=>$mchBillNo,
                'we_id'=>$work_message['receiver_we_id'],
                'openid'=>$openid,
                'total_amount'=>$work_message['settlement_amount'],
                'payment_amount'=>$payment_amount,
                'service_fee'=>$service_fee,
                'payment_account'=>1, // 1：伯乐天成、2：大悦
            ];

            // 发送红包并记录账单
            $redpackData = [
                'mch_billno'   => $mchBillNo,
                'send_name'    => '来飞网',
                're_openid'    => $openid,
                'total_amount' => env('APP_ENV') === 'production'? $payment_amount: 100, // 单位为分，不小于100,开发环境默认价格为1元
                'wishing'      => '您在来飞网的投稿已经审核通过啦，您的稿费请查收~',
                'act_name'     => '达人探店',
                'remark'       => '欢迎关注来飞网',
            ];
            $payment = Wechat::payment();
            $redpack = $payment->redpack;
            $result = $redpack->sendNormal($redpackData);

            if($result['result_code'] === 'SUCCESS'){ // 支付成功记录表格完成
                Log::notice('红包发送记录',['result'=>$result]);
                DB::table('explore_settlement')->insert($insert);
                DB::table('explore_settlement')->where('settlement_id','=',$last_settlement['settlement_id'])->update(['received' => 3]);
            } else { // 当状态为FAIL时，存在业务结果未明确的情况。所以如果状态是FAIL，请务必再请求一次查询接口[请务必关注错误代码（err_code字段），通过查询得到的红包状态确认此次发放的结果。]，以确认此次发放的结果。
                //记录FAIL
                Log::debug('红包支付状态FAIL,$mchBillNo为'.$mchBillNo.',即将重试');
                $result = $redpack->info($mchBillNo); // 再请求一次查询接口以确认此次发放的结果;
                if($result['result_code'] === 'SUCCESS'){ // 如果查询已经发放成功，继续后续流程
                    Log::notice('红包发送记录',['result'=>$result]);
                    DB::table('explore_settlement')->insert($insert);
                    DB::table('explore_settlement')->where('settlement_id','=',$last_settlement['settlement_id'])->update(['received' => 3]);
                } else { // 确认发放失败
                    Log::error('红包发送失败',$result);
                    throw new \Exception($result['return_msg']);
                }
            }
            DB::commit();
        } catch (\Exception $e) {
            DB::rollBack();
            Log::error(LaifeiWorkReSettlementController::class, ['msg' => $e->getMessage(), 'file' => $e->getFile(), 'line' => $e->getLine()]);
            return $this->setReturnJson(-1, '补发红包失败：'.$e->getMessage(), ['msg' => $e->getMessage(), 'file' => $e->getFile(), 'line' => $e->getLine()]);
        }
        return $this->setReturnJson(0,'补发成功');
    }

}
